<!-- components/PdfViewer.vue -->
<template>
  <div class="pdf-viewer">
    <canvas ref="canvasRef"></canvas>
    <div class="pager">
      <button @click="prevPage" :disabled="page <= 1">上一页</button>
      <span>{{ page }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="page >= totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import * as pdfjsLib from 'pdfjs-dist'

// 使用官方提供的 worker
// import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min.js?url'
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker

const props = defineProps({
  src: {
    type: [String, Object], // 支持 URL 或 File
    required: true,
  },
})

const canvasRef = ref(null)
const page = ref(1)
const totalPages = ref(0)
let pdfDoc = null

const renderPage = async (num) => {
  const pageObj = await pdfDoc.getPage(num)
  const viewport = pageObj.getViewport({ scale: 1.5 })

  const canvas = canvasRef.value
  const context = canvas.getContext('2d')

  canvas.height = viewport.height
  canvas.width = viewport.width

  const renderContext = {
    canvasContext: context,
    viewport: viewport,
  }

  await pageObj.render(renderContext).promise
}

const loadPdf = async () => {
  let source = props.src

  if (source instanceof File) {
    const buffer = await source.arrayBuffer()
    source = { data: buffer }
  }

  try {
    const loadingTask = pdfjsLib.getDocument(source)
    pdfDoc = await loadingTask.promise
    totalPages.value = pdfDoc.numPages
    page.value = 1
    renderPage(page.value)
  } catch (err) {
    console.error('PDF 加载失败:', err)
  }
}

onMounted(loadPdf)

const prevPage = () => {
  if (page.value > 1) {
    page.value--
    renderPage(page.value)
  }
}

const nextPage = () => {
  if (page.value < totalPages.value) {
    page.value++
    renderPage(page.value)
  }
}
</script>

<style scoped>
.pdf-viewer {
  text-align: center;
}
canvas {
  max-width: 100%;
  border: 1px solid #ddd;
}
.pager {
  margin-top: 10px;
}
</style>
